import React, { useState, useEffect } from 'react';
import { Box, Container, Typography, CircularProgress, Dialog, DialogTitle, DialogContent, TextField, DialogActions, Button, IconButton } from '@mui/material';
import QrCodeScannerIcon from '@mui/icons-material/QrCodeScanner';
import SettingsIcon from '@mui/icons-material/Settings';
import { getLoginQrCode,getLoginStatus } from '../services/messageService';

const LoginPage = () => {
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const [openSettings, setOpenSettings] = useState(false);
  const [host, setHost] = useState('https://api.example.com');
  const [apiToken, setApiToken] = useState('');
  const [adminToken, setAdminToken] = useState('');
  const [forceSettings, setForceSettings] = useState(false);

  const fetchQrCode = async () => {
  setIsLoading(true);
  try {
    const qrCodeUrl = await getLoginQrCode();
    if(qrCodeUrl===1) {
      window.location.href = '/chat';
    }
    setQrCodeUrl(qrCodeUrl);
  } catch (err) {
    setError(err.message);
  } finally {
    setIsLoading(false);
  }
};

useEffect(() => {
  // 检查localStorage中是否有host和apiToken配置
  const savedHost = localStorage.getItem('apiHost');
  const savedToken = localStorage.getItem('apiToken');
  
  if (!savedHost || !savedToken) {
    setForceSettings(true);
    setOpenSettings(true);
  }else{
    fetchQrCode();
    
    // 5秒后开始每秒检查登录状态
    const delayTimer = setTimeout(() => {
      const intervalId = setInterval(async () => {
        const isLoggedIn = await getLoginStatus();
        if (isLoggedIn) {
          clearInterval(intervalId);
          window.location.href = '/chat';
        }
      }, 1000);
      
      return () => clearInterval(intervalId);
    }, 5000);
    
    return () => clearTimeout(delayTimer);
  }
}, [setQrCodeUrl]);

  return (
    <Box 
      sx={{
        position: 'fixed',
        top: 0,
        left: 0,
        width: '100vw',
        height: '100vh',
        backgroundImage: 'url(/images/wallhaven-4g3gde.webp)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        animation: 'fadeIn 0.8s ease-out',
        '@keyframes fadeIn': {
          '0%': { opacity: 0 },
          '100%': { opacity: 1 }
        }
      }}
    >
      <Container 
        className="login-container page-transition-enter-active"
        sx={{
          backgroundColor: 'rgba(255, 255, 255, 0.95)',
          borderRadius: 4,
          padding: 4,
          textAlign: 'center',
          width: '380px',
          minHeight: '420px',
          boxShadow: '0 10px 30px rgba(0, 0, 0, 0.1)',
          transition: 'all 0.3s ease',
          '&:hover': {
            boxShadow: '0 15px 35px rgba(0, 0, 0, 0.15)',
            transform: 'translateY(-5px)'
          },
          position: 'relative'
        }}
      >
              <Typography variant="h5" sx={{ 
          fontWeight: 'bold', 
          mb: 1,
          color: '#333',
          alignSelf: 'flex-start'
        }}>
          扫码登录
        </Typography>
        {isLoading ? (
          <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
            <div className="loading-spinner" style={{ width: '40px', height: '40px' }}></div>
          </Box>
        ) : error ? (
          <Box sx={{ mt: 2, color: 'error.main' }}>
            <Typography variant="body1">{error}</Typography>
            <Button 
              variant="contained" 
              color="primary" 
              onClick={fetchQrCode} 
              sx={{ mt: 2 }}
              className="animated-button"
            >
              重试
            </Button>
          </Box>
        ) : qrCodeUrl ? (
          <Box 
            className="qrcode-container" 
            sx={{ 
              mt: 3,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              animation: 'fadeIn 0.5s ease-out'
            }}
          >
            <img 
              src={qrCodeUrl} 
              alt="微信登录二维码" 
              style={{ 
                width: '200px', 
                height: '200px',
                borderRadius: '8px',
                transition: 'all 0.3s ease'
              }} 
            />
            <Typography 
              variant="body2" 
              sx={{ 
                mt: 2, 
                color: 'text.secondary',
                backgroundColor: 'rgba(126, 217, 87, 0.1)',
                padding: '8px 16px',
                borderRadius: '20px',
                fontWeight: 500
              }}
            >
              请使用微信扫描二维码登录
            </Typography>
          </Box>
        ) : (
          <QrCodeScannerIcon sx={{ 
            fontSize: 80, 
            color: '#07c160',
            mb: 2,
            transition: 'transform 0.3s ease',
            '&:hover': {
              transform: 'scale(1.1)'
            }
          }} />
        )}
  
        
        {qrCodeUrl ? (
          <Typography variant="body1" sx={{ 
            color: '#666',
            mt: 'auto',
            alignSelf: 'flex-end'
          }}>
            请使用微信扫描二维码
          </Typography>
        ) : (
          <Typography variant="body1" sx={{ 
            color: '#666',
            mt: 'auto',
            alignSelf: 'flex-end'
          }}>
            正在获取登录二维码...
          </Typography>
        )}
        <Box sx={{ 
          position: 'absolute', 
          bottom: 16, 
          right: 16,
          display: 'flex',
          justifyContent: 'flex-end'
        }}>
          <IconButton 
            onClick={() => {
              const savedHost = localStorage.getItem('apiHost');
              const savedToken = localStorage.getItem('apiToken');
              if (savedHost) setHost(savedHost);
              if (savedToken) setApiToken(savedToken);
              setOpenSettings(true);
            }}
            sx={{ color: '#666', '&:hover': { color: '#07c160' } }}
          >
            <SettingsIcon />
          </IconButton>
        </Box>
      </Container>

      <Dialog open={openSettings} onClose={() => setOpenSettings(false)}>
        <DialogTitle>API设置</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            label="Host"
            type="url"
            fullWidth
            variant="standard"
            value={host}
            onChange={(e) => setHost(e.target.value)}
          />
          {(!apiToken || apiToken === '') && (
            <TextField
              margin="dense"
              label="Admin Token"
              type="password"
              fullWidth
              variant="standard"
              value={adminToken}
              onChange={(e) => setAdminToken(e.target.value)}
            />
          )}
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
            <TextField
              margin="dense"
              label="API Token"
              type="password"
              fullWidth
              variant="standard"
              value={apiToken}
              onChange={(e) => setApiToken(e.target.value)}
            />
            <Button 
              variant="outlined" 
              size="small"
              onClick={async () => {
                if (adminToken && host) {
                  try {
                    const response = await fetch(`${host}/admin/GenAuthKey2?key=${adminToken}`);
                    if (!response.ok) throw new Error('获取API Token失败');
                    const data = await response.json();
                    if (data.Code === 200) {
                      setApiToken(data.Data[0]);
                    } else {
                      throw new Error(data.Text || '获取API Token失败');
                    }
                  } catch (err) {
                    setError(err.message);
                  }
                }
              }}
              disabled={!adminToken || !host}
              sx={{ 
                textTransform: 'none',
                color: '#07c160',
                borderColor: '#07c160',
                '&:hover': {
                  borderColor: '#07c160',
                  backgroundColor: 'rgba(7, 193, 96, 0.04)'
                }
              }}
            >
              获取
            </Button>
          </Box>
        </DialogContent>
        <DialogActions>
          {!forceSettings && <Button onClick={() => setOpenSettings(false)}>取消</Button>}
          <Button onClick={async () => {
            localStorage.setItem('apiHost', host);
            localStorage.setItem('apiToken', apiToken);
            setOpenSettings(false);
            setIsLoading(true);
            const isLoggedIn = await getLoginStatus();
            if (isLoggedIn) {
              window.location.href = '/chat';
            }
            try {
              const qrCodeUrl = await getLoginQrCode();
              setQrCodeUrl(qrCodeUrl);
            } catch (err) {
              setError(err.message);
            } finally {
              setIsLoading(false);
            }
            setOpenSettings(false);
          }}>保存</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default LoginPage;